package utils;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @program: ocr_auto_app
 * @description:
 * @author: YB
 * @create: 2022-08-08 14:16
 **/
public class WindowsUtils {
    /**
     * 截图：指定屏幕区域
     * 参数为截图左上角坐标(x1,y1)+右下角坐标(x2,y2)
     */
    public static BufferedImage captureImg(int x1, int y1, int x2, int y2) throws Exception {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        BufferedImage subimage = image.getSubimage(x1, y1, x2, y2);
        return subimage;
    }

    /**
     * 截图：指定窗口(使用AWT)
     */
    public static BufferedImage captureWindowAndActive(WinDef.HWND hWnd) throws AWTException, IOException {
        WinDef.RECT r = new WinDef.RECT();
        Rectangle rect;
        User32.INSTANCE.GetWindowRect(hWnd, r);
        User32.INSTANCE.ShowWindow(hWnd, User32.INSTANCE.SW_SHOWNORMAL); //如果最小化，恢复显示
        User32.INSTANCE.SetForegroundWindow(hWnd); //激活显示
        rect = r.toRectangle();
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(rect);
        return image;
    }
}
